package com.service;

import org.springframework.stereotype.Service;

import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

@Service
public class BluetoothService {

    private final UUID uuid = new UUID("00001101-0000-1000-8000-00805F9B34FB", false);

    public void connect(String deviceName, String passkey) throws BluetoothStateException, IOException {
        LocalDevice localDevice = LocalDevice.getLocalDevice();
        DiscoveryAgent agent = localDevice.getDiscoveryAgent();

        RemoteDevice remoteDevice = null;
        for (RemoteDevice d : agent.retrieveDevices(DiscoveryAgent.PREKNOWN)) {
            if (d.getFriendlyName(false).equals(deviceName)) {
                remoteDevice = d;
                break;
            }
        }

        if (remoteDevice == null) {
            throw new RuntimeException("Device not found: " + deviceName);
        }

        String url = "btspp://" + remoteDevice.getBluetoothAddress() + ":" + uuid.toString() + ";authenticate=true;encrypt=true;master=false";
        StreamConnectionNotifier notifier = (StreamConnectionNotifier) Connector.open(url);

        // 等待连接
        StreamConnection connection = notifier.acceptAndOpen();

        // 进行身份验证
        if (!authenticate(connection, passkey)) {
            throw new RuntimeException("Authentication failed");
        }

        // 与蓝牙设备建立连接后可以进行读写操作
        InputStream inputStream = connection.openInputStream();
        OutputStream outputStream = connection.openOutputStream();

        // 在此进行读写操作

        // 关闭连接
        inputStream.close();
        outputStream.close();
        connection.close();
    }

    private boolean authenticate(StreamConnection connection, String passkey) throws IOException {
        RemoteDevice device = RemoteDevice.getRemoteDevice(connection);
        String deviceName = device.getFriendlyName(false);

        // 计算要求的PIN码
        byte[] pin = (passkey + deviceName).getBytes();

        // 进行身份验证
        return LocalDevice.getLocalDevice().setPin(pin);
    }
}
